<template>
  <div class="search-suggection">
    <van-cell icon="search" v-for="(text, index) in suggestions" :key="index" :title="text" @click="$emit('search', text)">
      <div v-html="highlight(text)" slot="title"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search.js'
// 按需加载有好处：只会把使用到的成员打包到结果中
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  data() {
    return {
      suggestions: []
    }
  },
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  methods: {
    async loadSearchSuggestions(q) {
      try {
        const { data } = await getSearchSuggestions(q)
        // console.log(data)
        this.suggestions = data.data.options
      } catch (err) {
        this.$toast('数据获取失败', err)
      }
    },
    highlight(text) {
      if (!text) return `<span class="active">${this.searchText}</span>`
      const highlightStr = `<span class="active">${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, highlightStr)
    }
  },
  watch: {
    searchText: {
      // eslint-disable-next-line space-before-function-paren
      handler: debounce(function (value) {
        this.loadSearchSuggestions(value)
      }, 200),
      immediate: true
    }
  }
}
</script>

<style lang="less" scoped>
.search-suggection {
  /deep/span.active {
    color: #3296fa;
  }
}
</style>
